<?php

/**
 * Controller Plugin for acl.
 * Intercept the request and validate it before it is dispached. 
 *
 * @author andrea
 */
class CMS_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract 
{
    public function preDispatch(Zend_Controller_Request_Abstract $request) 
    {
        // Setup acl
        $acl = new Zend_Acl();
        
        // Add the roles
        $acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'), 'guest');
        $acl->addRole(new Zend_Acl_Role('admin'), 'user');
        
        // Add the resources
        $acl->add(new Zend_Acl_Resource('default/index'));
        $acl->add(new Zend_Acl_Resource('default/proposta'));
        $acl->add(new Zend_Acl_Resource('default/search'));
        $acl->add(new Zend_Acl_Resource('default/guida'));
        $acl->add(new Zend_Acl_Resource('default/error'));
        $acl->add(new Zend_Acl_Resource('default/iscrizione'));
        $acl->add(new Zend_Acl_Resource('default/admin'));
        
        $acl->add(new Zend_Acl_Resource('cms/user'));
        
        $acl->add(new Zend_Acl_Resource('contact/index'));
        
        // Access rules
        $acl->allow('guest', 'default/index', array('index', 'show', 'archivio'));
        $acl->allow('guest', 'default/proposta', array('index', 'showbycat', 'show', 'noproposte'));
        $acl->allow('guest', 'default/search', array('index', 'search-proposte'));
        $acl->allow('guest', 'default/guida', array('index'));
        $acl->allow('guest', 'contact/index');
        $acl->allow('guest', 'cms/user', array('create'));
        
        // Privileges for authenticated users
        $acl->allow('user', 'cms/user');
        $acl->allow('user', 'default/iscrizione', array('index'));
        // All privileges for admin
        $acl->allow('admin', NULL);
        
        // Fetch the current user
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $role = $identity->userRole;
        } else {
            $role = 'guest';
        }
        
        
        $module = $request->module;
        $controller = $request->controller;
        $action = $request->action;
        $resource = $module . '/' . $controller;
        
        if (!$acl->isAllowed($role, $resource, $action)) {
            if ($role == 'guest') {
                $request->setModuleName('cms');
                $request->setControllerName('user');
                $request->setActionName('login');
            } else {
                $request->setControllerName('error');
                $request->setActionName('noauth');
            }
        }
        
        parent::preDispatch($request);
    }
}
